package com.me.launcher.custom;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

import com.me.launcher.R;
import com.me.launcher.adapter.BottomAdapter;
import com.me.launcher.inter.DragStatus;
import com.me.launcher.tools.LogUtil;
import com.me.launcher.tools.ScreenUtils;
import com.me.launcher.tools.Tools;

public class GragGridBottomView extends GridView {
    private static final int DRAG_IMG_SHOW = 1;
    private static final int DRAG_IMG_NOT_SHOW = 0;
    private static final String LOG_TAG = "DragGridView";
    private static final float AMP_FACTOR = 1.2f;

    /**
     * 被拖动的视图
     */
    private ImageView mDragImageView;
    private WindowManager.LayoutParams mDragViewParams;
    private WindowManager mWindowManager;
    private boolean mbIsViewOnDrag = false;

    /**
     * 前一次拖动的位置
     */
    private int preDraggedOverPositon = AdapterView.INVALID_POSITION;
    public int downRawX;
    private int downRawY;

    private OnDragListener mOnDragListener;
    private Drawable mDrawable;


    private int space;

    /**
     * 代表是否把热键区的app拖拽到了apps区
     */
    private boolean mDraging = false;

    /**
     * 长按选中拖动item
     */
    private OnItemLongClickListener onLongClickListener = new OnItemLongClickListener() {

        @Override
        //长按item开始拖动
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            if (((BottomAdapter) getAdapter()).getItem(position).getActivityInfo() == null) {
                return true;
            }
//            float iconLeft=(position%5*(ScreenUtils.getInstance().getScreenW()/5))+view.findViewById(R.id.img_icon).getX();
//            if (downRawX < iconLeft || downRawX > (iconLeft + view.findViewById(R.id.img_icon).getWidth())) {
//                return true;
//            }

            //记录长按item位置
            preDraggedOverPositon = position;

            //获取被长按item的drawing cache
            view.destroyDrawingCache();
            view.setDrawingCacheEnabled(true);
            //通过被长按item，获取拖动item的bitmap
            Bitmap dragBitmap = Bitmap.createBitmap(view.getDrawingCache());



            //设置拖动item为原item 1.2倍
            mDragViewParams.width = dragBitmap.getWidth();//(int) (AMP_FACTOR * dragBitmap.getWidth());
            mDragViewParams.height = dragBitmap.getHeight();//(int) (AMP_FACTOR * dragBitmap.getHeight());
            //设置触摸点为绘制拖动item的中心
            mDragViewParams.x = (downRawX - mDragViewParams.width / 2);
            mDragViewParams.y = (downRawY - mDragViewParams.height / 2-getResources().getDimensionPixelSize(ScreenUtils.getInstance().getStatusBarHeight()));
//            mDragViewParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
//                    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
//                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;


            //dragImageView为被拖动item的容器，清空上一次的显示
//            if ((int) mDragImageView.getTag() == DRAG_IMG_SHOW) {
//                mWindowManager.removeView(mDragImageView);
//                mDragImageView.setTag(DRAG_IMG_NOT_SHOW);
//            }

            if (mDragImageView.isAttachedToWindow()) {
                mWindowManager.removeView(mDragImageView);
                mDragImageView.setTag(DRAG_IMG_NOT_SHOW);
            }

            //设置本次被长按的item
            mDragImageView.setImageBitmap(dragBitmap);

            //添加拖动item到屏幕
            mWindowManager.addView(mDragImageView, mDragViewParams);
            mDragImageView.setTag(DRAG_IMG_SHOW);
            mbIsViewOnDrag = true;
            mDrawable = mDragImageView.getDrawable();
            //设置被长按item不显示
            ((BottomAdapter) getAdapter()).hideView(position);
            if (mOnDragListener != null) {
                mOnDragListener.onDrag(DragStatus.Drag_start);
                mOnDragListener.onDragApp(((BottomAdapter) getAdapter()).getItem(position).getActivityInfo().packageName);
            }
            return true;
        }
    };


    public GragGridBottomView(Context context) {
        super(context);
        initView();
    }

    public void initView() {
        setOnItemLongClickListener(onLongClickListener);
        //初始化显示被拖动item的image view
        mDragImageView = new ImageView(getContext());
        mDragImageView.setTag(DRAG_IMG_NOT_SHOW);
        //初始化用于设置dragImageView的参数对象
        mDragViewParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_TOAST,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS|
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);

        //设置拖动item的参数
        mDragViewParams.gravity = Gravity.TOP | Gravity.LEFT;

        mDragViewParams.format = PixelFormat.TRANSLUCENT;
        mDragViewParams.windowAnimations = 0;

        //获取窗口管理对象，用于后面向窗口中添加dragImageView
        mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        space = (int) (ScreenUtils.getInstance().getScreenH() - ScreenUtils.getInstance().dp2px(20 + 20 + 10 + 5) - getResources().getDimension(R.dimen.x35) - ScreenUtils.getInstance().sp2px(13));
    }

    public GragGridBottomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public GragGridBottomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    public void setIsViewOnDrag(boolean mbIsViewOnDrag) {
        this.mbIsViewOnDrag = mbIsViewOnDrag;
    }

    public void resetViewOnDrag() {
        preDraggedOverPositon = AdapterView.INVALID_POSITION;
    }


    public void setOnDragListener(OnDragListener listener) {
        mOnDragListener = listener;
    }

    public WindowManager.LayoutParams getDragViewParams() {
        return mDragViewParams;
    }

    public void setDragViewParams(WindowManager.LayoutParams dragViewParams) {
        this.mDragViewParams = dragViewParams;

    }

    public ImageView getDragImageView() {
        return mDragImageView;
    }

    public void setDragImageView(ImageView dragImageView) {
        this.mDragImageView = dragImageView;
        mbIsViewOnDrag = true;
        mDrawable = this.mDragImageView.getDrawable();
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
//        Logger.d("onTouchEvent==" + (ev.getAction() == MotionEvent.ACTION_MOVE) + "==" + mbIsViewOnDrag);

        //被按下时记录按下的坐标
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取触摸点相对于屏幕的坐标
            downRawX = (int) ev.getRawX();
            downRawY = (int) ev.getRawY();
        }
        //dragImageView处于被拖动时，更新dragImageView位置
        else if ((ev.getAction() == MotionEvent.ACTION_MOVE) && (mbIsViewOnDrag == true)) {
            //设置触摸点为dragImageView中心
            if (mOnDragListener != null) {
                mOnDragListener.onDragLocation(ev.getRawX(), ev.getRawY());


            }
            //如果拖拽到了apps区
            if (ev.getRawY() < space) {
                //让给apps区来处理触摸事件
                mOnDragListener.onDragEvent(ev);
                mDraging = true;
                return true;
            } else {
                //如果热键区的app 被拖拽后又拖拽回来
                if (((BottomAdapter) getAdapter()).isMbSetEmpty()) {
                    //还原刚刚remove的app数据
                    ((BottomAdapter) getAdapter()).setRemoveDrag();
                    mOnDragListener.onCancleDragEvent();
                    mDraging = false;
                }
                mDragViewParams.x = (int) (ev.getRawX() - mDragImageView.getWidth() / 2);
                mDragViewParams.y = (int) (ev.getRawY() - mDragImageView.getHeight() / 2-getResources().getDimensionPixelSize(ScreenUtils.getInstance().getStatusBarHeight()));
                //更新窗口显示
                mWindowManager.updateViewLayout(mDragImageView, mDragViewParams);
                //获取当前触摸点的item position
                int currDraggedPosition = ((int) ev.getX() / (ScreenUtils.getInstance().getScreenW() / 5));
//                int currDraggedPosition = pointToPosition((int) ev.getX(), (int) ev.getY());
                //如果当前停留位置item不等于上次停留位置的item，交换本次和上次停留的item
                if ((currDraggedPosition != AdapterView.INVALID_POSITION) && (currDraggedPosition != preDraggedOverPositon)) {

                    if (((BottomAdapter) getAdapter()).swapView(preDraggedOverPositon, currDraggedPosition)) {

                        preDraggedOverPositon = currDraggedPosition;
                    }
                }

            }
        }
        //释放dragImageView
        else if ((ev.getAction() == MotionEvent.ACTION_UP) && (mbIsViewOnDrag == true)) {
            ((BottomAdapter) getAdapter()).setMbSetEmpty(false);

            //在非本区域up
            if (mDraging) {
                mOnDragListener.onDragEvent(ev);
                mDraging = false;

                if ((int) mDragImageView.getTag() == DRAG_IMG_SHOW) {
                    mWindowManager.removeView(mDragImageView);
                    mDragImageView.setTag(DRAG_IMG_NOT_SHOW);
                }
                mbIsViewOnDrag = false;
                return true;
            }
            ((BottomAdapter) getAdapter()).showHideView();
            if (mOnDragListener != null) {
                mOnDragListener.onDrag(DragStatus.Drag_end);
            }
            if ((int) mDragImageView.getTag() == DRAG_IMG_SHOW) {
                mWindowManager.removeView(mDragImageView);
                mDragImageView.setTag(DRAG_IMG_NOT_SHOW);
            }
            preDraggedOverPositon = AdapterView.INVALID_POSITION;
            mbIsViewOnDrag = false;
        }
        return super.onTouchEvent(ev);
    }

    //设置变色
    public void setAlphaBitmap(int mColor) {
//          BitmapDrawable mBitmapDrawable = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.enemy_infantry_ninja);
//          Bitmap mBitmap = mBitmapDrawable.getBitmap();

        //BitmapDrawable的getIntrinsicWidth（）方法，Bitmap的getWidth（）方法
        //注意这两个方法的区别
        //Bitmap mAlphaBitmap = Bitmap.createBitmap(mBitmapDrawable.getIntrinsicWidth(), mBitmapDrawable.getIntrinsicHeight(), Config.ARGB_8888);
        Bitmap mAlphaBitmap = Bitmap.createBitmap(mDragViewParams.width, mDragViewParams.height, Bitmap.Config.ARGB_8888);

        Canvas mCanvas = new Canvas(mAlphaBitmap);
//        PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(mColor, PorterDuff.Mode.MULTIPLY);
        Paint mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
//        mPaint.setColorFilter(colorFilter);
//        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        mPaint.setColor(mColor);
        //从原位图中提取只包含alpha的位图
        Bitmap alphaBitmap = Tools.drawableToBitmap(mDrawable, 1.2f).extractAlpha();
        //在画布上（mAlphaBitmap）绘制alpha位图
        mCanvas.drawBitmap(alphaBitmap, 0, 0, mPaint);
        mDragImageView.setImageBitmap(mAlphaBitmap);
    }

    public void setOriginalBitmap() {
        mDragImageView.setImageDrawable(mDrawable);
    }

    public interface OnDragListener {
        /**
         * 拖拽app的包名
         *
         * @param pkgName
         */
        void onDragApp(String pkgName);

        /**
         * 拖拽状态
         *
         * @param status 开始和结束
         */
        void onDrag(@DragStatus int status);

        /**
         * 根据触摸点 判断是否滑动到删除和应用信息位置
         *
         * @param eventX
         * @param eventY
         */
        void onDragLocation(float eventX, float eventY);

        /**
         * 触摸事件分发给apps区
         *
         * @param ev
         */
        void onDragEvent(MotionEvent ev);


        /**
         * 拖拽到apps区域的后又回来
         */
        void onCancleDragEvent();



    }
}